const roleModel = require("../../model/role");
const userModel = require("../../model/user");
const paging = require("../../utils/paging");

// 获取角色列表
exports.getRoleList = async (req, res, next) => {
	try {
		const { getPaginatedResults, total } = await paging({
			model: roleModel,
			req,
			filterCallback: (query) => {
				if (req.query.name) query.name = new RegExp(req.query.name);
			},
		});
		const ret = await getPaginatedResults().sort({ _id: -1 });

		res.json({ code: 200, msg: "获取角色列表成功", data: { data: ret, total } });
	} catch (error) {
		res.json({ code: 500, msg: "获取角色列表失败" });
		next({ msg: "获取角色列表失败", error });
	}
};

// 新增角色
exports.addRole = async (req, res, next) => {
	try {
		const ret = await roleModel.create(req.body);
		res.json({ code: 200, msg: "新增角色成功", data: ret });
	} catch (error) {
		res.json({ code: 500, msg: "新增角色失败" });
		next({ msg: "新增角色失败", error });
	}
};

// 修改角色
exports.updateRole = async (req, res, next) => {
	try {
		const ret = await roleModel.updateOne({ _id: req.body._id }, req.body);
		res.json({ code: 200, msg: "修改角色成功", data: ret });
	} catch (error) {
		res.json({ code: 500, msg: "修改角色失败" });
	}
};

// 删除角色
exports.deleteRole = async (req, res, next) => {
	try {
		// 查询拥有该角色的用户, 并为用户删除该角色
		await userModel.updateMany({ role: req.body.id }, { $pull: { role: req.body.id } });
		// 删除角色
		const ret = await roleModel.deleteOne({ _id: req.body.id });
		res.json({ code: 200, msg: "删除角色成功", data: ret });
	} catch (error) {
		res.json({ code: 500, msg: "删除角色失败" });
		next({ msg: "删除角色失败", error });
	}
};
